package com.zerox.controller;


import com.alibaba.fastjson.JSON;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.zerox.domain.TableVO;
import com.zerox.pojo.Supplier;
import com.zerox.pojo.SysUser;
import com.zerox.service.SupplierService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("supplier")
public class SupplierController {

    @GetMapping("/tolist2")
    public String toList(){
        return "supplier";
    }

    @GetMapping("/toadd")
    public String toAdd(){
        return "addSupplier";
    }

    @Autowired
    private SupplierService supplierService;

    @GetMapping(value = "/list2",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String listSupplier(Integer page,Integer limit,String supContact){

        List<Supplier> list = supplierService.list(supContact ,page, limit);

        int count = supplierService.count(supContact);

        TableVO tableVO = new TableVO(0, count, list, "");

        String string = JSON.toJSONString(tableVO);

        return string;
    }

    @GetMapping("/viewSupplier/{id}")
    public String selectById(Model model,@PathVariable Integer id){

        Supplier supplier = supplierService.selectById(id);

        model.addAttribute("supplier",supplier);

        return "viewSupplier";
    }

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id){

        int result = supplierService.delete(id);

        return result > 0 ? "1" : "0";

    }

    @PostMapping("/addSupplier")
    public String add(Model model, @Valid Supplier supplier, BindingResult bindingResult, MultipartFile idPic, HttpServletRequest request) throws IOException {

        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error"+fieldError.getDefaultMessage());
            }
            return "addSupplier";
        }

        if (idPic != null) {
            if (idPic.getSize() > 2000000) {
                model.addAttribute("idPicPath", "文件不能超过2M");
                return "add";
            }

            String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

            if (".jpg.png".indexOf(suffix) == -1) {
                model.addAttribute("idPicPath", "文件格式不正确，不能上传");
                return "add";
            }

            //指定文件存储的目录
            String path = request.getSession().getServletContext().getRealPath("statics") + File.separator + "supImg";  // ?

            String fileName = RandomUtils.nextInt(1000000) + "_pic" + suffix;

            File fileTo = new File(path + File.separator + fileName);
            System.out.println(path + File.separator + fileName);
            //如果文件不存在就创建
            if (!fileTo.exists()) {
                fileTo.mkdirs();
            }
            //核心代码,将文件存储到指定位置
            idPic.transferTo(fileTo);

            supplier.setIdpicpath(fileName);
        }

        int add = supplierService.add(supplier);

        if (add > 0) {
            model.addAttribute("msg",true);
            return "redirect:tolist2";
        }

        model.addAttribute("msg",false);

        return "addSupplier";
    }

    @GetMapping("/update/{userid}")
    public String viewupdate(Model model,@PathVariable("userid") Integer id){

        Supplier supplier = supplierService.selectById(id);

        model.addAttribute("supplier",supplier);

        return "updateSupplier";
    }

    @PostMapping("/updateSupplier/{id}")
    public String update(Model model,@Valid Supplier supplier,BindingResult bindingResult,@PathVariable Integer id,MultipartFile idPic,HttpServletRequest request) throws IOException {

        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error"+fieldError.getDefaultMessage());
            }
            return "updateSupplier";
        }

        if (idPic.getSize() > 200000) {
            model.addAttribute("idPicPath"+"文件不能超过2M");
            return "update";
        }

        //指定文件存储的目录
        String path = request.getSession().getServletContext().getRealPath("statics") + File.separator + "supImg";  // ?
        String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

        String fileName = RandomUtils.nextInt(1000000) + "_pic" + suffix;

        File fileTo = new File(path+File.separator+fileName);
        System.out.println(path+File.separator+fileName);
        //如果文件不存在就创建
        if (!fileTo.exists()) {
            fileTo.mkdirs();
        }
        //核心代码,将文件存储到指定位置
        idPic.transferTo(fileTo);

        supplier.setId(id);
        supplier.setIdpicpath(fileName);

        int update = supplierService.update(supplier);

        model.addAttribute("msg", update > 0);

        return "updateSupplier";
    }

    @GetMapping(value = "/supInfo/{id}",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String supInfo(@PathVariable Integer id){

        Supplier supplier = supplierService.selectById(id);
        String sup = JSON.toJSONString(supplier);

        return sup;
    }

    @GetMapping("/codeExists")
    @ResponseBody
    public String codeExists(String supCode){
        Supplier supplier = supplierService.selectByCode(supCode);
        if (supplier==null){
            return "0";
        }
        return "1";
    }
}
